/*
Class Name:OverrideMaterialNew
Function: override Material New Button, according to UI(Material Allocation)
Author: Shuai Cao(shuaicao@isoftstone.com)

*/
with sharing public class OverrideMaterialNew
{
    public String IdSelect{get;set;}
    Set<Material__Share> MatShare = new Set<Material__Share>();
    public String msg{get;set;}
    public String msg1{get;set;}

    public String Prefix = Material__c.sObjectType.getDescribe().getKeyPrefix();  
    Decimal total = 0;
     public Material__c Mat{
         get{
             if(Mat == null)
                 Mat = new Material__c();
             Mat.Date__c = date.today();
             return Mat;
         }
         set;
     }
     public List<HospitalMaterial__c> HosMatList{
         get{
            return HosMatList;
         }
         set;
     }
     public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');
           }  
        set;
    }   
        
    public List<SelectOption> options{
        get{
             if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
            
            List<Place__c> PList = new List<Place__c>();
            List<String> citys = new List<String>();  
            Profile RSMprofile = [Select p.Name, p.Id From Profile p where Name =: GlobalProperties.ProfileRSM_M ];  
            Profile RSMTprofile = [Select p.Name, p.Id From Profile p where Name =: GlobalProperties.ProfileRSM_TM]; 
             
            User Uinfo = [Select UserCity__c,UserSubRegion__c,ProfileId  From user Where id =: UserInfo.getUserId()]; 
            
            if((Uinfo.ProfileId  == RSMprofile.id)||(Uinfo.ProfileId  == RSMTprofile.id))
            {
                Place__c SubRegion = [Select id,Name From Place__c Where Name =: Uinfo.UserSubRegion__c];
                PList = [Select id,Name From Place__c Where Subregion__c =: SubRegion.id and PlaceType__c =: GlobalProperties.CityType];               
            }
            else{
                if(Uinfo.UserCity__c.contains(GlobalProperties.SplitSymbol))
                {
                    citys = Uinfo.UserCity__c.split(GlobalProperties.SplitSymbol,0);
                }
                else
                {
                    citys.add(Uinfo.UserCity__c);
                }
                PList = [Select id,Name From Place__c Where Name in: citys ];
            }
            
            options.add(new SelectOption('1',''));
            for(Place__c p : PList){
                options.add(new SelectOption(p.Id,p.Name)); 
            }   
            return  options;             
        }
        set;
    } 
    public PageReference  actionSupport()
    {
        if(HosMatList == null)
            HosMatList = new List<HospitalMaterial__c>();
        else
            HosMatList.clear();
       
       Mat = null;
            
       List<Hospital__c> HosList = [Select id,Name,class__c,Active__c,City__r.name,ownerid From Hospital__c Where City__c =: IdSelect and (Active__c =: true or approvalstatus__c =: GlobalProperties.ApprovedButNotEffective) order by ownerid];
       Mat.City__c = IdSelect; 
       Set<Id> uIds = new Set<Id>(); 

       for(Hospital__c hos : HosList)
       {
           uIds.add(hos.ownerid);
       }
       List<User> uList = [Select id,Alias From User Where id in: uIds];
       for(Hospital__c hos : HosList)
       {
           for(User u : uList)
           {
               if(hos.ownerid == u.id)
               {
                   HospitalMaterial__c HM = new HospitalMaterial__c();
                   HM.MSR__c = u.Alias;
                   HM.ownerid = hos.ownerid;
                   HM.City__c = hos.City__r.name;
                   HM.Hospital__c = hos.id;
                   HM.Hospital_Class__c = hos.class__c;
                   HM.Name =  hos.name;
                   HM.HospitalActive__c = hos.Active__c;
                   HosMatList.add(HM);
                   
               }
           }
       
       }       

        return null;      
            
    }

 
    public OverrideMaterialNew(ApexPages.StandardController controller){
        this.controller=controller;
        
        Mat.Date__c = date.today();
        Mat.AllocatedNumber__c = 0;

        total = 0;
    }
       
    
    public PageReference SaveAndNew()
    {
        msg = null;
        msg1 = null;

        if(HosMatList != null){
            for(HospitalMaterial__c hm : HosMatList)
            {
                if((hm.Number__c != 0)&&(hm.Number__c != null)){
                    total += hm.Number__c;
                }
            }
        } 
        
        if((IdSelect == null) || (IdSelect == '1'))
        {
            msg = '城市不能为空';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }
        if(Mat.Materical_Start_Date__c == null)
        {
            msg = '物料开始日期不能为空';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }
        if(Mat.Materical_End_Date__c == null)
        {
            msg = '物料结束日期不能为空';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }
        if(Mat.Material__c == null)
        {
            msg = '物料不能为空';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        } 
        if(Mat.Total_Number__c == null)
        {
            msg = '物料总数不能为空';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        } 
                                
    
        if(total  > Mat.Total_Number__c)
        {
            msg = '已分配数超过物料总数';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }

        if(Mat.Materical_Start_Date__c > Mat.Materical_End_Date__c)
        {
            msg = '开始日期不能晚于结束日期';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }  
        if(Mat.Materical_Start_Date__c<= date.today())
        {
            msg = '开始日期需选择明天及以后';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }    
                
        if(total  < Mat.Total_Number__c)
        {
            msg1 = '分配量小于物料总量，保存成功';
        }  
        else if(total  == Mat.Total_Number__c)
        {
            msg1 = '保存成功';
        }
        Boolean haveNum = false;
        for(HospitalMaterial__c hm : HosMatList)
        {
            if((hm.Number__c != 0)&&(hm.Number__c != null))
            {
                haveNum = false;
            }
            else
            {
                haveNum = true;
                break;
            }            
        }
        if(!haveNum)
        {
            msg = '未填写医院分配物料数';
            return null;
        }
                
        Mat.Name = string.valueof(Mat.Materical_Start_Date__c) + Mat.Material__c + '物料分配';
        Mat.AllocatedNumber__c = total;    
        insert Mat;
        
        List<HospitalMaterial__c> insertList = new List<HospitalMaterial__c>();
        
        for(HospitalMaterial__c hm : HosMatList)
        {
            if((hm.Number__c != 0)&&(hm.Number__c != null))
            {
                Material__Share mShare = new Material__Share();
                mShare.ParentId = Mat.id;
                mShare.UserOrGroupId = hm.ownerid;
                mShare.AccessLevel = GlobalProperties.ReadPermission;
                MatShare.add(mShare);   
                            
                hm.Material__c = Mat.id;
                hm.Name = string.valueof(Mat.Materical_Start_Date__c) + hm.name + '物料分配';
                insertList.add(hm);
            }
        }
        insert insertList;
        
        Set<id> MsrIds = new Set<id>();
        for(HospitalMaterial__c hm : insertList)
        {
            MsrIds.add(hm.ownerid);
            
        }
        List<User> MsrList = [Select id,Email,Alias From User Where id in: MsrIds];
        for(User u : MsrList)
        {
            List<String> toAddresses = new List<String>();
            toAddresses.add( u.Email );  
            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' + '您收到一个新的物料管理"' + Mat.Name +'"! \n' + string.valueof(Date.Today());
            String Subject = '物料管理';
                    
            EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);        
            
        }
       
        

        List<Material__Share> MatList = new List<Material__Share>();
        for(Material__Share m : MatShare)
        {
            MatList.add(m);
        }
        if(MatList.size() > 0)
            insert MatList;      
        
        //Mat = null;
        //HosMatList.clear();
        return null;
    }
        public PageReference Cancel()
    {

        PageReference pr=new PageReference('/' + Prefix);
        pr.setRedirect(true);
        return pr;
    }
    private final ApexPages.StandardController controller;
    
    static testMethod void OverrideViewTest()
    {
        Material__c add = new Material__c();
        add.name = 'test';
        add.Date__c = date.today();
        insert add;
        
        System.currentPageReference().getParameters().put('id', add.Id); 
        
        ApexPages.StandardController del = new ApexPages.StandardController(add);
        
        OverrideMaterialNew testCase = new OverrideMaterialNew(del);
        System.assert(testCase.options != null);
        testCase.actionSupport();
        testCase.SaveAndNew();
        testCase.Cancel();
    }
 
}